<template>
    <ElSpace>
        <ElButton :loading="loading" type="primary" @click="getList" v-valid="'classifyGet'">刷新</ElButton>
        <ElButton v-valid="'classifyAdd'" type="success" @click="classify = { pid: 0, sort: 5 }; dfRef.show()">添加</ElButton>
    </ElSpace>
    <p></p>
    <Table v-valid="'classifyGet'" :cols="cols" :data="list">
        <template #action="{ row }">
            <ElButton v-if="row.pid === 0" v-valid="'classifyAdd'" type="primary"
                @click="classify = { pid: row.id, sort: 5 }; dfRef.show();">添加分类
            </ElButton>
            <ElButton v-else v-valid="'attrsAdd'" type="primary" @click="attrs = { class_id: row.id }; attrsRef.show()">添加属性
            </ElButton>
            <ElButton v-if="row.pid > 0" v-valid="'attrsGet'" type="primary" @click="getAttrsList(row.id)">属性管理
            </ElButton>
            <ElButton v-valid="'classifyUpdate'" type="success" @click="classify = { ...row }; dfRef.show();">修改</ElButton>
            <ElButton v-valid="'classifyDelete'" type="danger" @click="del(row)">删除</ElButton>
        </template>
    </Table>
    <DF v-valid="['classifyAdd', 'classifyUpdate']" labelWidth="80px" :title="classify.id ? '修改分类' : '添加分类'"
        :model="classify" :options="options" @ok="ok" ref="dfRef" />
    <!-- 属性DF -->
    <DF v-valid="['attrsAdd', 'attrsUpdate']" labelWidth="80px" :title="attrs.id ? '修改属性' : '添加属性'" :model="attrs"
        :options="attrsOptions" @ok="confirmAtts" ref="attrsRef" />
    <Dialog ref="dialogRef" title="属性管理" @ok="dialogRef.hide()">
        <ElSpace v-loading="attrsLoading">
            <ElTag @click="() => {
                if (valid('attrsUpdate')) {
                    attrs = { ...item };
                    attrsRef.show();
                }
            }" size="large" @close="delAttrs(item)" v-for="item in attrsList" :key="item.id"
                :closable="valid('attrsDelete')">
                {{ item.name }}</ElTag>
        </ElSpace>
    </Dialog>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue';
import { add, update, deleteClass, getAll, IClassify, AddType } from '@/api/classify';
import { add as _add, update as _update, deleteAttrs as _del, getList as _getList, IAttrs, AddType as AttrsAddType, deleteAttrs } from '@/api/attrs';
import confirm from '@/components/Confirm';
import { valid } from '@/utils/common';
import { ElMessage } from 'element-plus';

/**
 * 原始分类列表
 */
const originClassify = ref<IClassify[]>([]);
/**
 * 列表
 */
const list = ref<IClassify[]>([]);
/**
 * 属性列表
 */
const attrsList = ref<IAttrs[]>([]);
/**
 * loading
 */
const loading = ref(false);
/**
 * 属性loading
 */
const attrsLoading = ref(false);
/**
 * 分类信息
 */
const classify = ref(<IClassify & AddType>{});
/**
 * 添加修改的属性
 */
const attrs = ref(<IAttrs & AttrsAddType>{});
/**
 * fd引用
 */
const dfRef = ref();
/**
 * 属性引用
 */
const attrsRef = ref();
/**
 * dialog引用
 */
const dialogRef = ref();
/**
 * table列
 */
const cols = {
    name: {
        title: '分类名称',
        align: 'left'
    },
    sort: {
        title: '排序'
    },
    action: {
        title: '操作',
        width: 380,
    }
}
/**
 * 表单配置项
 */
const options = computed(() => ({
    name: {
        title: '分类名称',
        required: true,
        max: 20,
        type: 'expand'
    },
    sort: {
        title: '排序',
        required: true,
        min: 0,
        width: '100px',
        type: 'number',
    },
    pid: {
        title: '父菜单',
        required: true,
        tag: 'select',
        values: [{ label: '顶级菜单', value: 0 }, ...list.value.map(({ id: value, name: label }) => ({ label, value }))]
    }
}
));
/**
 * 属性表单配置项
 */
const attrsOptions = computed(() => ({
    name: {
        title: '属性名称',
        required: true,
        max: 20,
    },
    class_id: {
        title: '分类',
        required: true,
        tag: 'select',
        values: originClassify.value.filter(c => c.pid > 0).map(({ id: value, name: label }) => ({ label, value }))
    }
}));
/**
 * 确定方法
 */
const ok = async (classify: IClassify) => {
    try {
        if (classify.id === classify.pid) {
            return ElMessage.warning('不能添加自己为父菜单');
        }
        dfRef.value.start();
        delete classify.children;
        await (classify.id ? update : add)(classify);
        getList();
        dfRef.value.hide();
    } catch (error) { }
    finally {
        dfRef.value.stop();
    }
}

/**
 * 获取分类列表
 */
const getList = async () => {
    if (!valid(['classifyGet', 'classifyAdd'])) return;
    try {
        loading.value = true;
        const data = await getAll();
        originClassify.value = [...data];
        const parents = data.filter(c => c.pid === 0);
        parents.forEach(item => {
            const children = data.filter(c => c.pid === item.id);
            children.length && (item.children = children.map(item => ({ ...item })));
        });
        list.value = parents;
    } catch (error) { }
    loading.value = false;
}

/**
 * 删除
 * @param roles 
 */
const del = async ({ id, name }: IClassify) => {
    let res: any;
    try {
        res = await confirm(`您确定要删除【${name}】吗？`);
        await deleteClass(id);
        getList();
    } catch (error) { }
    res && res();
}

/**
 * 获取属性列表
 */
const getAttrsList = async (id: number) => {
    dialogRef.value.show();
    attrsLoading.value = true;
    try {
        const list = await _getList(id);
        attrsList.value = list;
    } catch (error) { }
    attrsLoading.value = false;
}

/**
 * 提交属性
 * @param model 
 */
const confirmAtts = async (model: IAttrs) => {
    try {
        await (model.id ? _update : _add)(model);
        attrsRef.value.hide();
        model.id && getAttrsList(model.class_id);
    } catch (error) { }
    attrsRef.value.stop();
}

/**
 * 删除属性
 */
const delAttrs = async ({ id, name }: IAttrs) => {
    let res: any;
    try {
        res = await confirm(`您确定要删除【${name}】吗？`);
        await deleteAttrs(id);
        const index = attrsList.value.findIndex(c => c.id == id);
        attrsList.value.splice(index, 1);
    } catch (error) { }
    res & res();
}

getList();
</script>

<style></style>